package com.yundasys.lab02springbootstudy.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @PACKAGE_NAME: com.yundasys.lab02springbootstudy.future
 * @NAME: CompletableFutureMain
 * @USER: jiangta
 * @DATE: 2021/12/8
 * @TIME: 11:28 上午
 * @PROJECT_NAME: springboot-labs
 */
public class CompletableFutureMain {

    public static void main(String[] args) throws InterruptedException {
//        CompletableFuture<Double> cf = CompletableFuture.supplyAsync(CompletableFutureMain::fetchPrice);
//        cf.thenAccept( result -> {
//            System.out.println("price:" + result);
//        }).exceptionally( e -> {
//            e.printStackTrace();
//            return null;
//        });

        CompletableFuture<Double> cf2 = CompletableFuture.completedFuture(fetchPrice());


        try {
            Double aDouble = cf2.get();
            System.out.println("price:" + aDouble);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

// 主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:
        Thread.sleep(2000);


    }

    static double fetchPrice() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //if(Math.random() < 0.3) {
            throw new RuntimeException("fetch price failed!");
        //}
        //return 5 + Math.random()*20;
    }
}
